package com.example.sso.server.controller;

import com.example.sso.server.entity.ClientApp;
import com.example.sso.server.repository.ClientAppRepository;
import com.example.sso.server.repository.TokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class AuthorizationController {

    @Autowired
    private ClientAppRepository clientAppRepository;
    
    @Autowired
    private TokenRepository tokenRepository;

    @GetMapping("/oauth/authorize")
    public String authorize(
            @RequestParam("client_id") String clientId,
            @RequestParam("response_type") String responseType,
            @RequestParam("scope") String scope,
            @RequestParam("redirect_uri") String redirectUri,
            @RequestParam(value = "state", required = false) String state,
            @RequestParam(value = "Referer", required = false) String referer,
            Model model,
            HttpSession session) {
        
        // 验证客户端ID
        ClientApp clientApp = clientAppRepository.findByClientId(clientId);
        if (clientApp == null) {
            model.addAttribute("error", "无效的客户端ID");
            return "error";
        }
        
        // 验证响应类型
        if (!"code".equals(responseType)) {
            model.addAttribute("error", "不支持的响应类型");
            return "error";
        }
        
        // 验证scope
        if (!"user_info".equals(scope)) {
            model.addAttribute("error", "不支持的权限范围");
            return "error";
        }
        
        // 验证redirect_uri
        if (!clientApp.getRedirectUri().startsWith(redirectUri.split("\\?")[0])) {
            model.addAttribute("error", "重定向URI不匹配");
            return "error";
        }
        
        // 检查用户是否已登录
        String username = (String) session.getAttribute("username");
        if (username == null) {
            // 用户未登录，保存授权请求信息到session
            session.setAttribute("clientId", clientId);
            session.setAttribute("redirectUri", redirectUri);
            session.setAttribute("state", state);
            session.setAttribute("referer", referer);
            return "redirect:/login";
        }
        
        // 用户已登录，生成授权码并重定向到客户端
        String code = tokenRepository.generateCode();
        
        // 构建重定向URL
        StringBuilder redirectUrl = new StringBuilder(redirectUri);
        if (redirectUri.contains("?")) {
            redirectUrl.append("&");
        } else {
            redirectUrl.append("?");
        }
        redirectUrl.append("code=").append(code);
        
        if (state != null) {
            redirectUrl.append("&state=").append(state);
        }
        
        if (referer != null) {
            redirectUrl.append("&Referer=").append(URLEncoder.encode(referer, StandardCharsets.UTF_8));
        }
        
        return "redirect:" + redirectUrl.toString();
    }
}
    